﻿using System.Collections.Generic;
using UnityEngine;

namespace Zero.Dialogue
{
    public class DialogueSystem : MonoBehaviour
    {
        #region 单例模式

        public static DialogueSystem Instance { get; private set; }

        private void Awake()
        {
            Instance = this;
        }

        #endregion

        [Header("对话框")]
        public UI_DialoguePanel dialoguePanel;
        [Header("气泡")]
        [Tooltip("气泡的持续时间")]
        public float bubbleDuration = 3f;
        [Tooltip("气泡面板的模板")]
        public UI_BubblePanel bubblePanelTemplate;

        private Dictionary<BubbleCharacter, UI_BubblePanel>
            _bubbles = new Dictionary<BubbleCharacter, UI_BubblePanel>();

        /// <summary>
        /// 设置对话框文本
        /// </summary>
        /// <param name="characterName">角色名字</param>
        /// <param name="body">文本主体</param>
        public void SetDialogueText(string characterName, string body)
        {
            dialoguePanel.SetDialogueText(characterName, body);
        }

        /// <summary>
        /// 切换对话框面板
        /// </summary>
        public void ToggleDialoguePanel()
        {
            dialoguePanel.gameObject.SetActive(!dialoguePanel.gameObject.activeSelf);
        }

        public void ToggleDialoguePanel(bool active)
        {
            dialoguePanel.gameObject.SetActive(active);
        }

        #region 聊天气泡

        private UI_BubblePanel CreateBubble(BubbleCharacter character)
        {
            var bubblePanel = Instantiate(bubblePanelTemplate, bubblePanelTemplate.transform.parent);
            bubblePanel.gameObject.name = "Bubble Panel - " + character.characterName;
            bubblePanel.Bind(character, bubbleDuration);
            _bubbles.Add(character, bubblePanel);
            return bubblePanel;
        }

        public void ShowBubble(BubbleCharacter character, string body)
        {
            if (!_bubbles.TryGetValue(character, out var bubblePanel))
                bubblePanel = CreateBubble(character);
            bubblePanel.SetBody(body);
            bubblePanel.Show();
        }

        #endregion
    }
}